<template>
  <div class="help-center">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <el-button @click="handleBack" :icon="ArrowLeft" circle />
        <h1>帮助中心</h1>
        <div class="placeholder"></div>
      </div>

      <!-- 搜索框 -->
      <el-card class="search-card">
        <div class="search-section">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入您要咨询的问题关键词"
            size="large"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
            <template #suffix>
              <el-button type="primary" @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
        
        <!-- 热门搜索 -->
        <div class="hot-searches" v-if="!hasSearched">
          <span class="hot-label">热门搜索：</span>
          <el-tag
            v-for="(keyword, index) in hotSearches"
            :key="index"
            @click="searchKeyword = keyword; handleSearch()"
            class="hot-tag"
          >
            {{ keyword }}
          </el-tag>
        </div>
      </el-card>

      <!-- 搜索结果 -->
      <div v-if="hasSearched" class="search-results">
        <el-card>
          <h3>搜索结果 ({{ searchResults.length }})</h3>
          <div v-if="searchResults.length === 0" class="no-results">
            <el-empty description="未找到相关问题">
              <el-button type="primary" @click="hasSearched = false">返回帮助首页</el-button>
            </el-empty>
          </div>
          <div v-else class="results-list">
            <div
              v-for="result in searchResults"
              :key="result.id"
              class="result-item"
              @click="viewQuestion(result)"
            >
              <h4>{{ result.title }}</h4>
              <p>{{ result.summary }}</p>
              <div class="result-meta">
                <el-tag size="small">{{ result.category }}</el-tag>
                <span class="view-count">{{ result.viewCount }} 次查看</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 帮助分类 -->
      <div v-else class="help-categories">
        <h2>常见问题分类</h2>
        <div class="categories-grid">
          <el-card
            v-for="category in helpCategories"
            :key="category.id"
            class="category-card"
            @click="enterCategory(category)"
          >
            <div class="category-content">
              <div class="category-icon">
                <el-icon :size="32" :color="category.color">
                  <component :is="category.icon" />
                </el-icon>
              </div>
              <div class="category-info">
                <h3>{{ category.name }}</h3>
                <p>{{ category.description }}</p>
                <span class="question-count">{{ category.questionCount }} 个问题</span>
              </div>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 常见问题 -->
      <div v-if="!hasSearched" class="faq-section">
        <h2>热门问题</h2>
        <el-card>
          <el-collapse v-model="activeFAQ">
            <el-collapse-item
              v-for="faq in popularFAQs"
              :key="faq.id"
              :title="faq.question"
              :name="faq.id"
            >
              <div class="faq-content">
                <div v-html="faq.answer"></div>
                <div class="faq-actions">
                  <el-button size="small" @click="likeFAQ(faq)">
                    <el-icon><ThumbsUp /></el-icon>
                    有用 ({{ faq.likeCount }})
                  </el-button>
                  <el-button size="small" @click="dislikeFAQ(faq)">
                    <el-icon><ThumbsDown /></el-icon>
                    无用 ({{ faq.dislikeCount }})
                  </el-button>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </div>

      <!-- 联系我们 -->
      <div v-if="!hasSearched" class="contact-section">
        <h2>联系我们</h2>
        <div class="contact-grid">
          <el-card class="contact-card" @click="openCustomerService">
            <div class="contact-content">
              <el-icon :size="24" color="#409eff"><ChatDotRound /></el-icon>
              <div class="contact-info">
                <h4>在线客服</h4>
                <p>7×24小时在线为您服务</p>
              </div>
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-card>

          <el-card class="contact-card" @click="callService">
            <div class="contact-content">
              <el-icon :size="24" color="#67c23a"><Phone /></el-icon>
              <div class="contact-info">
                <h4>客服热线</h4>
                <p>400-123-4567</p>
              </div>
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-card>

          <el-card class="contact-card" @click="sendEmail">
            <div class="contact-content">
              <el-icon :size="24" color="#e6a23c"><Message /></el-icon>
              <div class="contact-info">
                <h4>邮件反馈</h4>
                <p>service@laundry.com</p>
              </div>
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 问题详情对话框 -->
      <el-dialog
        v-model="showQuestionDialog"
        :title="selectedQuestion?.title"
        width="700px"
      >
        <div class="question-detail" v-if="selectedQuestion">
          <div class="question-meta">
            <el-tag>{{ selectedQuestion.category }}</el-tag>
            <span class="view-count">{{ selectedQuestion.viewCount }} 次查看</span>
            <span class="update-time">更新于 {{ formatDate(selectedQuestion.updatedAt) }}</span>
          </div>
          
          <div class="question-content" v-html="selectedQuestion.content"></div>
          
          <div class="question-actions">
            <h4>这个回答对您有帮助吗？</h4>
            <div class="action-buttons">
              <el-button @click="rateQuestion(selectedQuestion, true)">
                <el-icon><ThumbsUp /></el-icon>
                有帮助 ({{ selectedQuestion.helpfulCount }})
              </el-button>
              <el-button @click="rateQuestion(selectedQuestion, false)">
                <el-icon><ThumbsDown /></el-icon>
                没帮助 ({{ selectedQuestion.unhelpfulCount }})
              </el-button>
            </div>
          </div>

          <div class="related-questions" v-if="relatedQuestions.length > 0">
            <h4>相关问题</h4>
            <div class="related-list">
              <div
                v-for="related in relatedQuestions"
                :key="related.id"
                class="related-item"
                @click="viewQuestion(related)"
              >
                {{ related.title }}
              </div>
            </div>
          </div>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="showQuestionDialog = false">关闭</el-button>
            <el-button type="primary" @click="openCustomerService">联系客服</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ArrowLeft,
  Search,
  ChatDotRound,
  Phone,
  Message,
  ArrowRight,
  ThumbsUp,
  ThumbsDown,
  QuestionFilled,
  Setting,
  ShoppingCart,
  CreditCard,
  User,
  House
} from '@element-plus/icons-vue'
import { helpApi } from '@/services/api'
import dayjs from 'dayjs'

const router = useRouter()

// 数据定义
const searchKeyword = ref('')
const hasSearched = ref(false)
const searchResults = ref([])
const activeFAQ = ref([])
const showQuestionDialog = ref(false)
const selectedQuestion = ref(null)
const relatedQuestions = ref([])

// 热门搜索关键词
const hotSearches = ref([
  '如何下单', '支付问题', '订单取消', '评价规则', '优惠券使用', '账户安全'
])

// 帮助分类
const helpCategories = ref([
  {
    id: 1,
    name: '订单问题',
    description: '下单、取消、修改等订单相关问题',
    icon: ShoppingCart,
    color: '#409eff',
    questionCount: 15
  },
  {
    id: 2,
    name: '支付问题',
    description: '支付方式、退款、发票等支付相关问题',
    icon: CreditCard,
    color: '#67c23a',
    questionCount: 12
  },
  {
    id: 3,
    name: '账户问题',
    description: '注册登录、信息修改、密码找回等',
    icon: User,
    color: '#e6a23c',
    questionCount: 8
  },
  {
    id: 4,
    name: '服务问题',
    description: '服务质量、时间安排、特殊要求等',
    icon: House,
    color: '#f56c6c',
    questionCount: 20
  },
  {
    id: 5,
    name: '其他问题',
    description: '优惠活动、意见建议、投诉举报等',
    icon: QuestionFilled,
    color: '#909399',
    questionCount: 10
  }
])

// 热门FAQ
const popularFAQs = ref([
  {
    id: 1,
    question: '如何下单预约服务？',
    answer: `
      <p>下单步骤如下：</p>
      <ol>
        <li>在首页选择您需要的服务类型</li>
        <li>浏览并选择合适的服务商家</li>
        <li>选择服务时间和地址</li>
        <li>确认订单信息并提交</li>
        <li>完成支付即可</li>
      </ol>
      <p>如有疑问，可随时联系在线客服。</p>
    `,
    likeCount: 128,
    dislikeCount: 3
  },
  {
    id: 2,
    question: '支持哪些支付方式？',
    answer: `
      <p>我们支持以下支付方式：</p>
      <ul>
        <li>支付宝</li>
        <li>微信支付</li>
        <li>银行卡支付</li>
        <li>账户余额支付</li>
      </ul>
      <p>所有支付都经过银行级别的安全加密，请放心使用。</p>
    `,
    likeCount: 96,
    dislikeCount: 2
  },
  {
    id: 3,
    question: '如何取消已下单的订单？',
    answer: `
      <p>取消订单的方法：</p>
      <ol>
        <li>进入"我的订单"页面</li>
        <li>找到需要取消的订单</li>
        <li>点击"取消订单"按钮</li>
        <li>选择取消原因并确认</li>
      </ol>
      <p><strong>注意：</strong>不同状态的订单取消规则不同，请查看具体订单的取消说明。</p>
    `,
    likeCount: 84,
    dislikeCount: 5
  }
])

// 生命周期
onMounted(() => {
  // 模拟数据加载
})

// 方法定义
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    ElMessage.warning('请输入搜索关键词')
    return
  }

  hasSearched.value = true
  
  try {
    // 模拟搜索结果
    searchResults.value = [
      {
        id: 1,
        title: '如何下单预约服务？',
        summary: '详细介绍下单预约服务的完整流程，包括选择服务、商家、时间等步骤...',
        category: '订单问题',
        viewCount: 1256
      },
      {
        id: 2,
        title: '支付失败怎么办？',
        summary: '当支付出现问题时的解决方法，包括检查网络、余额、银行卡状态等...',
        category: '支付问题',
        viewCount: 892
      }
    ].filter(item => 
      item.title.includes(searchKeyword.value) || 
      item.summary.includes(searchKeyword.value)
    )
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请重试')
  }
}

const enterCategory = (category) => {
  // 跳转到分类详情页面
  router.push(`/help/category/${category.id}`)
}

const viewQuestion = async (question) => {
  selectedQuestion.value = question
  showQuestionDialog.value = true
  
  // 增加查看次数
  question.viewCount++
  
  // 获取相关问题
  try {
    // 模拟相关问题
    relatedQuestions.value = [
      { id: 10, title: '下单后多久开始服务？' },
      { id: 11, title: '可以修改服务时间吗？' },
      { id: 12, title: '如何联系服务人员？' }
    ]
  } catch (error) {
    console.error('获取相关问题失败:', error)
  }
}

const likeFAQ = (faq) => {
  faq.likeCount++
  ElMessage.success('感谢您的反馈！')
}

const dislikeFAQ = (faq) => {
  faq.dislikeCount++
  ElMessage.info('我们会继续改进，感谢反馈！')
}

const rateQuestion = (question, isHelpful) => {
  if (isHelpful) {
    question.helpfulCount = (question.helpfulCount || 0) + 1
    ElMessage.success('感谢您的反馈！')
  } else {
    question.unhelpfulCount = (question.unhelpfulCount || 0) + 1
    ElMessage.info('我们会继续改进，感谢反馈！')
  }
}

const openCustomerService = () => {
  // 打开客服聊天窗口
  ElMessage.info('正在为您接入客服...')
  // 这里可以集成第三方客服系统
}

const callService = () => {
  // 拨打客服电话
  window.open('tel:4001234567')
}

const sendEmail = () => {
  // 发送邮件
  window.open('mailto:service@laundry.com')
}

const handleBack = () => {
  if (hasSearched.value) {
    hasSearched.value = false
    searchKeyword.value = ''
    searchResults.value = []
  } else {
    router.back()
  }
}

const formatDate = (date) => {
  return dayjs(date).format('YYYY-MM-DD')
}
</script>

<style lang="scss" scoped>
.help-center {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 20px 0;
}

.container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  h1 {
    margin: 0;
    font-size: 24px;
    font-weight: 600;
    color: #333;
  }

  .placeholder {
    width: 32px;
  }
}

.el-card {
  margin-bottom: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.search-card {
  .search-section {
    margin-bottom: 16px;
  }

  .hot-searches {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: wrap;

    .hot-label {
      color: #666;
      font-size: 14px;
      white-space: nowrap;
    }

    .hot-tag {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-1px);
      }
    }
  }
}

.search-results {
  h3 {
    margin: 0 0 16px 0;
    font-size: 18px;
    color: #333;
  }

  .no-results {
    padding: 40px 20px;
    text-align: center;
  }

  .results-list {
    .result-item {
      padding: 16px;
      border-bottom: 1px solid #f0f0f0;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background-color: #f8f9fa;
      }

      &:last-child {
        border-bottom: none;
      }

      h4 {
        margin: 0 0 8px 0;
        font-size: 16px;
        color: #333;
      }

      p {
        margin: 0 0 12px 0;
        color: #666;
        font-size: 14px;
        line-height: 1.5;
      }

      .result-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .view-count {
          color: #999;
          font-size: 12px;
        }
      }
    }
  }
}

.help-categories {
  h2 {
    margin: 0 0 24px 0;
    font-size: 20px;
    color: #333;
  }

  .categories-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 16px;

    .category-card {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        transform: translateY(-2px);
      }

      .category-content {
        display: flex;
        align-items: center;
        gap: 16px;

        .category-icon {
          flex-shrink: 0;
        }

        .category-info {
          flex: 1;

          h3 {
            margin: 0 0 8px 0;
            font-size: 16px;
            color: #333;
          }

          p {
            margin: 0 0 8px 0;
            color: #666;
            font-size: 14px;
            line-height: 1.4;
          }

          .question-count {
            color: #999;
            font-size: 12px;
          }
        }
      }
    }
  }
}

.faq-section {
  h2 {
    margin: 0 0 16px 0;
    font-size: 20px;
    color: #333;
  }

  .faq-content {
    color: #666;
    line-height: 1.6;

    :deep(ol), :deep(ul) {
      padding-left: 20px;
    }

    :deep(li) {
      margin-bottom: 4px;
    }

    .faq-actions {
      margin-top: 16px;
      padding-top: 16px;
      border-top: 1px solid #f0f0f0;
      display: flex;
      gap: 12px;
    }
  }
}

.contact-section {
  h2 {
    margin: 0 0 16px 0;
    font-size: 20px;
    color: #333;
  }

  .contact-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 16px;

    .contact-card {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
        transform: translateY(-1px);
      }

      .contact-content {
        display: flex;
        align-items: center;
        gap: 12px;

        .contact-info {
          flex: 1;

          h4 {
            margin: 0 0 4px 0;
            font-size: 16px;
            color: #333;
          }

          p {
            margin: 0;
            color: #666;
            font-size: 14px;
          }
        }
      }
    }
  }
}

.question-detail {
  .question-meta {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;

    .view-count,
    .update-time {
      color: #999;
      font-size: 12px;
    }
  }

  .question-content {
    color: #333;
    line-height: 1.6;
    margin-bottom: 24px;

    :deep(ol), :deep(ul) {
      padding-left: 20px;
    }

    :deep(li) {
      margin-bottom: 4px;
    }
  }

  .question-actions {
    margin-bottom: 24px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #333;
    }

    .action-buttons {
      display: flex;
      gap: 12px;
    }
  }

  .related-questions {
    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      color: #333;
    }

    .related-list {
      .related-item {
        padding: 8px 12px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        margin-bottom: 8px;
        cursor: pointer;
        transition: all 0.3s ease;
        color: #409eff;
        font-size: 14px;

        &:hover {
          background-color: #f0f9ff;
          border-color: #409eff;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .container {
    padding: 0 10px;
  }

  .page-header {
    h1 {
      font-size: 20px;
    }
  }

  .categories-grid {
    grid-template-columns: 1fr;
  }

  .contact-grid {
    grid-template-columns: 1fr;
  }

  .hot-searches {
    .hot-label {
      width: 100%;
      margin-bottom: 8px;
    }
  }

  .result-meta {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style> 